package com.rsscollector.controller.admin.action;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.FileAppender;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.rsscollector.util.Log4JUtil;

public class ViewLogFilesAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		Map<String, Integer> logFiles = new Hashtable<String, Integer>();

		for (Iterator<FileAppender> it = Log4JUtil.getAllFileAppenders().iterator(); it.hasNext();) {
			FileAppender fileAppender = it.next();
			Integer count = new Integer(countLogFileNum(fileAppender));
			logFiles.put(fileAppender.getFile(), count);
		}

		request.setAttribute("logFiles", logFiles);
		
		return mapping.findForward("success");
	}
	
    private int countLogFileNum(FileAppender fileAppender) throws IOException {
    	int count = 0;
        File logFile = new File(fileAppender.getFile());
        String logFileName = logFile.getName();
        File logFolder = logFile.getParentFile();
        for (String childFileName : logFolder.list()) {
            if (childFileName.startsWith(logFileName)) {
                count++;
            }
        }
        return count;
    }	
}
